import os
import sys
import shutil
import tempfile

# 支持的图片扩展名
IMAGE_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp')

def get_first_image_in_folder(folder_path):
    """获取文件夹中的第一张图片"""
    try:
        # 获取文件夹中的所有文件
        files = [f for f in os.listdir(folder_path) 
                if os.path.isfile(os.path.join(folder_path, f))]
        
        # 过滤出图片文件并按文件名排序
        image_files = [f for f in files if f.lower().endswith(IMAGE_EXTENSIONS)]
        image_files.sort()
        
        if image_files:
            return os.path.join(folder_path, image_files[0])
        return None
    except Exception as e:
        print(f"读取文件夹失败 {os.path.basename(folder_path)}: {str(e)}")
        return None

def set_folder_cover(folder_path, image_path):
    """设置文件夹封面为 folder.jpg"""
    try:
        # 检查并删除已存在的封面文件（包括不同扩展名的）
        for ext in IMAGE_EXTENSIONS:
            cover_path = os.path.join(folder_path, f'folder{ext}')
            if os.path.exists(cover_path):
                try:
                    os.remove(cover_path)
                    print(f"删除已存在的 folder{ext}")
                except Exception as e:
                    print(f"删除已存在的 folder{ext} 失败: {str(e)}")
        
        # 直接复制并重命名图片
        cover_path = os.path.join(folder_path, 'folder.jpg')
        shutil.copy2(image_path, cover_path)
        print(f"创建封面文件: {cover_path}")
        
        return True
    except Exception as e:
        print(f"设置文件夹封面失败: {str(e)}")
        return False

def main():
    # 获取当前目录
    current_dir = os.getcwd()
    print(f"当前目录: {current_dir}")
    
    # 获取所有子文件夹
    subfolders = [f for f in os.listdir(current_dir) 
                 if os.path.isdir(os.path.join(current_dir, f))]
    
    if not subfolders:
        print("当前文件夹中没有子文件夹")
        return
    
    print(f"找到 {len(subfolders)} 个子文件夹")
    
    # 处理每个子文件夹
    success_count = 0
    for folder in subfolders:
        try:
            folder_path = os.path.join(current_dir, folder)
            image_path = get_first_image_in_folder(folder_path)
            
            if image_path:
                if set_folder_cover(folder_path, image_path):
                    success_count += 1
                    print(f"成功为文件夹 '{folder}' 设置封面")
                else:
                    print(f"为文件夹 '{folder}' 设置封面失败")
            else:
                print(f"在文件夹 '{folder}' 中未找到图片")
        except Exception as e:
            print(f"处理文件夹 '{folder}' 时出错: {str(e)}")
    
    print(f"\n完成! 成功设置了 {success_count} 个文件夹的封面")
    
    # 提示用户可能需要手动刷新
    print("\n注意: 如果封面没有立即显示，请尝试按 F5 刷新文件资源管理器")

if __name__ == "__main__":
    main()